import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutterapp/models/community.dart';
import 'package:flutterapp/models/general_type.dart';
import 'package:flutterapp/models/room_app_liance_item.dart';
import 'package:flutterapp/page/home/common_title/index.dart';
import 'package:flutterapp/page/utils/common_toast.dart';
import 'package:flutterapp/page/utils/dio_http.dart';
import 'package:flutterapp/page/utils/scopoed_model_helper.dart';
import 'package:flutterapp/page/utils/string_is_null_or_entity.dart';
import 'package:flutterapp/page/utils/upload_images.dart';
import 'package:flutterapp/page/widgets/common_floating_action_button.dart';
import 'package:flutterapp/page/widgets/common_form_item.dart';
import 'package:flutterapp/page/widgets/common_image_picker/index.dart';
import 'package:flutterapp/page/widgets/common_radio_form_item.dart';
import 'package:flutterapp/page/widgets/common_select_form_item.dart';
import 'package:flutterapp/page/widgets/room_appliance.dart';
import 'package:flutterapp/scoped_model/auth.dart';

class RoomAddPage extends StatefulWidget {
  const RoomAddPage({Key key}) : super(key: key);

  @override
  _RoomAddPageState createState() => _RoomAddPageState();
}

class _RoomAddPageState extends State<RoomAddPage> {
  //三个数据列表
  //装修
  List<GeneralType> floorList = [];
  //户型
  List<GeneralType> orientedList = [];
  //楼层
  List<GeneralType> roomTypeList = [];

  //装修  租赁方式
  int rentType = 0;
  int decorationType = 0;

  //户型 楼层 朝向......
  int roomType = 0;
  int floor = 0;
  int oriented = 0;

  Community community;

  //房屋配置
  List<RoomAppLianceItem> applianceList = [];

  List<File> images = [];
  String imageList = "";

  var titleController = TextEditingController();
  var descController = TextEditingController();

  var sizeController = TextEditingController();
  var priceController = TextEditingController();

  _getParams() async {
    var token = await ScopedModelHelper.getModel<AuthModel>(context).token;
    print(token);
    try {
      //参数

      String url = '/houses/params';

      //返回处理
      var res = await DioHttp.of(context).get(url);
      var data = json.decode(res.toString())['body'];
      print(data);
      List<GeneralType> floorList = List<GeneralType>.from(
          data['floor'].map((item) => GeneralType.fromJson(item)));
      List<GeneralType> orientedList = List<GeneralType>.from(
          data['oriented'].map((item) => GeneralType.fromJson(item)));
      List<GeneralType> roomTypeList = List<GeneralType>.from(
          data['roomType'].map((item) => GeneralType.fromJson(item)));

      setState(() {
        this.floorList = floorList;
        this.orientedList = orientedList;
        this.roomTypeList = roomTypeList;
      });
    } catch (e) {}
  }

  //提交的时候同时获取上面获取的所有参数
  _submit() async {
    var size = sizeController.text;
    var price = priceController.text;
    //数据校验
    if (stringIsNullOrEmpty(size)) {
      CommonToast.showToast('【大小】不能为空');
      return;
    }
    if (stringIsNullOrEmpty(price)) {
      CommonToast.showToast('【租金】不能为空');
      return;
    }
    // .....其它另做校验

    //返回的图片字符串length
    var imageString = await uploadimages(images, context);
    CommonToast.showToast(imageString);
    setState(() {
      imageList = imageString;
    });

    var appliancstr = "";
    for (var i = 0; i < applianceList.length; i++) {
      if (applianceList[i].isChecked) {
        appliancstr += applianceList[i].title.toString() + ",";
      }
    }
    Map<String, dynamic> params = {
      "title": titleController.text, //标题
      "description": descController.text, //描述
      "price": priceController.text, //租金
      "size": sizeController.text, //大小
      "oriented": orientedList[oriented].name, //列表里面的第几个
      "roomType": roomTypeList[roomType].name, //类型
      "floor": floorList[floor].name, //朝向
      "community": community.id, //小区
      "houseImg": imageString.toString(), //房屋图片
      "supporting": appliancstr.toString(), //房屋配置
    };
    print(appliancstr);
    try {
      //数据请求
      var url = '/room/add';
      //var token = ScopedModelHelper.getModel<AuthModel>(context).token;
      var token = ScopedModelHelper.getModel<AuthModel>(context).token;
      //print(token.toString());r
      var res = await DioHttp.of(context).post(url, params, token);
      //接受返回值,如果成功 跳转到上一层
      ////
      ///
      CommonToast.showToast("房源发布成功");
      bool isSubmitted = true;
      Navigator.of(context).pop(isSubmitted);

      //如果没有请求成功
      //弹出后端返回的错误提示信息................................

      print('打印....tokne..');
      print(token);
      print(params);
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    Timer.run(_getParams);
    //获取城市id

    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //位置居中
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      //底部浮动
      floatingActionButton: CommonFloatingActionButton('提交', _submit),
      appBar: AppBar(
        title: Text('房源发布'),
        centerTitle: true,
      ),
      body: ListView(
        children: [
          CommonTitle('房源信息'),
          CommonFormItem(
            label: '小区',
            contentBuild: (context) {
              return Container(
                // GestureDetector 添加事件
                child: GestureDetector(
                  //点击空白区域生效事件
                  behavior: HitTestBehavior.translucent,
                  child: Container(
                    height: 40.0,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          community?.name ?? '请选择小区',
                          style: TextStyle(
                            fontSize: 16.0,
                          ),
                        ),
                        Icon(Icons.keyboard_arrow_right)
                      ],
                    ),
                  ),
                  onTap: () {
                    //携带...cityId  返回的路由接收一个对象.......并复制到选择框
                    var result =
                        Navigator.of(context).pushNamed('/communityPkcker');
                    result.then((value) => {
                          if (null != value)
                            setState(() {
                              community = value;
                            })
                        });
                  },
                ),
              );
            },
          ),
          CommonFormItem(
            label: '租金',
            hintText: '请输入租金',
            suffixText: '元/月',
            controller: priceController,
          ),
          CommonFormItem(
              label: '大小',
              hintText: '请输入房屋大小',
              suffixText: '平方米',
              controller: sizeController),
          CommonRadioFormItem(
              label: '装修',
              options: ['精装', '简装'],
              value: rentType,
              onChange: (index) {
                setState(() {
                  rentType = index;
                });
              }),
          if (floorList.length > 0)
            CommonSelectFormItem(
              label: '户型',
              value: roomType,
              onChange: (val) {
                setState(() {
                  roomType = val;
                });
              },
              options: floorList.map((e) => e.id).toList(),
            ),
          //
          if (orientedList.length > 0)
            CommonSelectFormItem(
              label: '楼层',
              value: floor,
              onChange: (val) {
                setState(() {
                  floor = val;
                });
              },
              options: orientedList.map((e) => e.id).toList(),
            ),
          if (roomTypeList.length > 0)
            CommonSelectFormItem(
              label: '朝向',
              value: oriented,
              onChange: (val) {
                setState(() {
                  oriented = val;
                });
              },
              options: roomTypeList.map((e) => e.id).toList(),
            ),
          CommonRadioFormItem(
              label: '租赁方式',
              options: ['简装', '精装', '豪装'],
              value: decorationType,
              onChange: (index) {
                setState(() {
                  decorationType = index;
                });
              }),
          CommonTitle('房屋头像'),
          CommonImagePicker(onChange: (List<File> files) {
            setState(() {
              images = files;
            });

            //print(imageString);
          }),
          CommonTitle('房屋标题'),
          Container(
            //左距
            padding: EdgeInsets.symmetric(horizontal: 10.0),
            child: TextField(
              controller: titleController,
              decoration: InputDecoration(
                  hintText: '请输入(例如:整租 小区;)', border: InputBorder.none),
            ),
          ),
          CommonTitle('房屋配置'),
          RoomAppLiance(
            onChange: (data) {
              applianceList = data;
            },
          ),
          CommonTitle('房屋描述'),
          Container(
            margin: EdgeInsets.only(bottom: 100.0),
            padding: EdgeInsets.symmetric(horizontal: 10.0),
            child: TextField(
              //事件
              controller: descController,
              //最大10行
              maxLines: 10,
              decoration: InputDecoration(
                  hintText: '请输入房屋描述', border: InputBorder.none),
            ),
          ),
        ],
      ),
    );
  }
}
